package main

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/trackertrader/goctp"
	ctp "gitee.com/trackertrader/goctp/lnx"
	//ctp "gitee.com/trackertrader/goctp/win"
)

var (
	quoteFront = "tcp://xxx:41313"
	tradeFront = "tcp://xxx:41305"
	brokerID   = ""
	investorID = ""
	password   = ""
	appID      = ""
	authCode   = ""
)

var t = ctp.NewTrade()
var q = ctp.NewQuote()

func init() {

}

func onTick(data *goctp.TickField) {
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
	if bs, err := json.Marshal(data); err == nil {
		println("tick:" + string(bs))
	} else {
		fmt.Print("ontick")
	}
}

func testQuote() {
	q.RegOnFrontConnected(func() {
		fmt.Println("quote connected")
		q.ReqLogin(investorID, password, brokerID)
	})
	q.RegOnRspUserLogin(func(login *goctp.RspUserLoginField, info *goctp.RspInfoField) {
		fmt.Println("quote login:", info)
		q.ReqSubscript("rb2404")
	})
	q.RegOnTick(onTick)
	fmt.Println("quote connecting " + quoteFront)
	q.ReqConnect(quoteFront)
}

func testTrade() {
	t.RegOnFrontConnected(func() {
		fmt.Println("trade connected")
		go t.ReqLogin(investorID, password, brokerID, appID, authCode)
	})
	t.RegOnRspUserLogin(func(login *goctp.RspUserLoginField, info *goctp.RspInfoField) {
		fmt.Println(info)
		fmt.Printf("trade login info: %v\n", *login)
	})
	t.RegOnRtnOrder(func(field *goctp.OrderField) {
		fmt.Printf("RtnOrder: %+v\n", *field)
		//fmt.Print("orderKey:", field.OrderSysID, field.StatusMsg)
		// t.Orders.Range(func(key, value interface{}) bool {
		// 	fmt.Print("orderKey:", key, value.(goctp.OrderField).StatusMsg)
		// 	return true
		// })
	})
	t.RegOnRtnTrade(func(field *goctp.TradeField) {
		fmt.Printf("RtnTrade: %+v\n", *field)
	})
	t.RegOnErrRtnOrder(func(field *goctp.OrderField, info *goctp.RspInfoField) {
		fmt.Printf("%v\n", info)
	})
	t.RegOnRtnInstrumentStatus(func(field *goctp.InstrumentStatus) {
		fmt.Printf("InstrumentStatus： %v\n", field)
	})
	t.RegOnFrontDisConnected(func(reason int) {
		fmt.Printf("%v\n", reason)
	})
	fmt.Println("connected to trade " + tradeFront)
	t.ReqConnect(tradeFront)
}

func main() {
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
	go testQuote() // 不能同时测试交易
	//go testTrade()
	for !t.IsLogin {
		time.Sleep(10 * time.Second)
	}
	cnt := 0
	//t.ReqOrderInsertMarket(5, "202310100005", "rb2401", goctp.DirectionBuy, goctp.OffsetFlagOpen, 1)

	// 开仓
	//key := t.ReqOrderInsert(15, "202310100015", "rb2401", goctp.DirectionBuy, goctp.OffsetFlagOpen, 4177, 1)
	//fmt.Println(key)

	time.Sleep(3 * time.Second)
	t.Instruments.Range(func(k, v interface{}) bool {
		// fmt.Printf("%v", v)
		cnt++
		return true
	})
	fmt.Printf("instrument count: %d\n", cnt)

	// t.RegOnRtnFromFutureToBank(func(field *goctp.TransferField) {
	// 	fmt.Print(field)
	// })
	// t.ReqFutureToBank("", "", 30)
	t.Release()
	q.Release()
	select {}
}
